﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using MyCRM.Infrastructure.Messaging;

namespace MyCRM.Infrastructure
{
    public abstract class AggregateRoot : IAggregateRoot
    {
        private readonly IList<DomainEvent> _changes = new List<DomainEvent>();

        public Guid AggregateId { get; set;  }

        public IEnumerable<DomainEvent> GetUncommittedChanges()
        {
            return _changes;
        }

        public void MarkChangesAsCommitted()
        {
            _changes.Clear();
        }

        public void ResotreFromEventHistory(IEnumerable<DomainEvent> history)
        {            
            foreach (var @event in history)
            {
                InvokeApplyMethodInConcreteType(FindApplyMethodInConcreteType(@event), @event);
            }
        }

        protected void ApplyChangeBy(DomainEvent domainEvent)
        {
            InvokeApplyMethodInConcreteType(FindApplyMethodInConcreteType(domainEvent), domainEvent);
            _changes.Add(domainEvent);
        }

        private MethodInfo FindApplyMethodInConcreteType(DomainEvent domainEvent)
        {
            return (from methodInfo in GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)
                    from parameterInfo in methodInfo.GetParameters()
                    where parameterInfo.ParameterType == domainEvent.GetType() && methodInfo.Name.Contains("Apply")
                    select methodInfo).Single();
        }

        private void InvokeApplyMethodInConcreteType(MethodInfo matchedMethod, DomainEvent domainEvent)
        {
            try
            {
                matchedMethod.Invoke(this, new[] { domainEvent });
            }
            catch (Exception error)
            {
                if(error.InnerException != null)
                    throw error.InnerException;
                throw;
            }
        }
    }
}